<?php

namespace app\pc\controller;


use basic\WapBasic;
use service\AlipayTradeWapService;
use service\UtilService;
use app\wap\model\activity\EventSignUp;
use service\JsonService;
use service\SystemConfigService;
use service\WxpayService;
use think\Url;
use think\Db;

use service\WechatTemplateService;
use app\wap\model\user\User;
use app\wap\model\store\StoreOrder;
use app\wap\model\store\StoreOrderStatus;
use app\wap\model\user\WechatUser;
use app\wap\model\user\MemberShip;
use app\admin\model\wechat\WechatMessage;
use app\wap\model\special\SpecialBuy;
use app\pc\model\tindex\Openvip;//会员卡
/**
 * 支付宝支付
 * Class Alipay
 * @package app\wap\controller
 */
class Paysuccess extends WapBasic
{
    protected function _initialize()
    {

            $wechat = SystemConfigService::more(['wechat_appid','wechat_appsecret','wechat_token']);
            $payment = SystemConfigService::more(['pay_weixin_mchid','pay_weixin_client_cert','pay_weixin_client_key','pay_weixin_key','pay_weixin_open']);
           
             $this->appid=isset($wechat['wechat_appid']) ? $wechat['wechat_appid']:'';
             $this->secret=isset($wechat['wechat_appsecret']) ? $wechat['wechat_appsecret']:'';
             $this->token=isset($wechat['wechat_token']) ? $wechat['wechat_token']:'';
             $this->mchid=$payment['pay_weixin_mchid'];
             $this->apiKey=$payment['pay_weixin_key'];

    }

    //会员购买成功
    public function wapay_success_notify($orderId,$cateid){
        $postStr = file_get_contents('php://input');
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        Db::name("wachatpay")->insert(array("te"=>$postStr));
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        if ($postObj === false) {
            die('parse xml error');
        }
        if ($postObj->return_code != 'SUCCESS') {
            die($postObj->return_msg);
        }
        if ($postObj->result_code != 'SUCCESS') {
            die($postObj->err_code);
        }
        $arr = (array)$postObj;
        unset($arr['sign']);
        
 
        if (self::getSign($arr, $config['key']) == $postObj->sign) {
            $order = Db::name("store_order")->where('order_id', $orderId)->where('type',1)->find();
            Openvip::updatestatus($orderId,$cateid,0);
            if(!$order) return false;
            $resMer = true;
            $res1 = Db::name("store_order")->where('order_id', $orderId)->where('type',1)->update(['paid' => 1, 'pay_time' => time()]);
            $oid = Db::name("store_order")->where('order_id', $orderId)->where('type',1)->value('id');
            $userInfo = User::getUserInfo($order['uid']);
            if($order['type'] && $res1  ){
                $resMer=MemberShip::getUserMember($order,$userInfo);
            }

            StoreOrderStatus::status($oid, 'pay_success', '用户付款成功');

           
        }
    }
    public function kepay_success($orderId){
        $postStr = file_get_contents('php://input');
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
       // Db::name("wachatpay")->insert());
        Db::name("wachatpay")->insert(array("te"=>$postStr,'tej'=>'special'.$orderId));
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        if ($postObj === false) {
            die('parse xml error');
        }
        if ($postObj->return_code != 'SUCCESS') {
            die($postObj->return_msg);
        }
        if ($postObj->result_code != 'SUCCESS') {
            die($postObj->err_code);
        }
        $arr = (array)$postObj;
        unset($arr['sign']);
        if (self::getSign($arr, $config['key']) == $postObj->sign) {
            
            $order = Db::name("store_order")->where('order_id', $orderId)->where('type',0)->find();
            if(!$order) return false;
            $resMer = true;
         
            $res1 = Db::name("store_order")->where('order_id', $orderId)->where('type',0)->update(['paid' => 1, 'pay_time' => time()]);
            StoreOrderStatus::status($order["id"], 'pay_success', '用户付款成功');
       
            User::bcInc($order['uid'], 'pay_count', 1, 'uid');
           
               //如果是专栏，记录专栏下所有专题购买。
            SpecialBuy::setAllBuySpecial($orderId, $order["uid"], $order["cart_id"]);
            try {
                   User::backOrderBrokerage($order);
            } catch (\Throwable $e) { }

           
        }
    }
 /**
     * curl get
     *
     * @param string $url
     * @param array $options
     * @return mixed
     */
    public static function curlGet($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function createNonceStr($length = 16)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    public static function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";
        return $xml;
    }
    /**
     * 获取签名
     */
    public static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
        return $signStr;
    }
    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }


}